#!/usr/bin/env python
#coding:utf-8

import wx
import wx.aui
import wx.lib.flatnotebook as FNB
import datetime
import time
import Globals
import Model
import LogWindow
import ShellWindow
import DomainWindow
import SPCWindow
import Database
import CalibWindow
import CountWindow
from sqlobject import *
from Debug import debug, error

ID_FILE_NEWPLAN = wx.NewId()
ID_EDIT_SHIFT = wx.NewId()
ID_EDIT_PREF = wx.NewId()
ID_EDIT_COOR = wx.NewId()
ID_TOOL_DEBUG = wx.NewId()
ID_TOOL_MANUAL = wx.NewId()
ID_TOOL_STATELOOK = wx.NewId()
ID_QUERY_SPINE = wx.NewId()
ID_QUERY_PRODUCT = wx.NewId()
ID_EDIT_USER = wx.NewId()
ID_QUERY_CATEGORY = wx.NewId()
ID_QUERY_PRODUCTTYPE = wx.NewId()
ID_QUERY_ENTITY = wx.NewId()
ID_QUERY_CALIBLOG = wx.NewId()
ID_QUERY_ASSCALIPER = wx.NewId()
ID_QUERY_ASSSPRING = wx.NewId()
ID_QUERY_S1 = wx.NewId()
ID_QUERY_S2_1 = wx.NewId()
ID_QUERY_S2_2 = wx.NewId()
ID_QUERY_S3_1 = wx.NewId()
ID_QUERY_S3_2 = wx.NewId()
ID_QUERY_S4_1 = wx.NewId()
ID_QUERY_S4_2 = wx.NewId()
ID_QUERY_S5_1 = wx.NewId()
ID_QUERY_S5_2 = wx.NewId()
ID_QUERY_S6_1 = wx.NewId()
ID_QUERY_S6_2 = wx.NewId()
ID_QUERY_S6_3 = wx.NewId()
ID_QUERY_S6_4 = wx.NewId()
ID_QUERY_S7 = wx.NewId()
ID_QUERY_PART = wx.NewId()
ID_TOOL_PRINTCODE = wx.NewId()
ID_TOOL_REPRINTCODE = wx.NewId()
ID_TOOL_EDITPART = wx.NewId()
ID_TOOL_PYCRUST = wx.NewId()
ID_TOOL_CLEARRES = wx.NewId()
ID_TOOL_CALIB = wx.NewId()
ID_TOOL_CLRCOUNT = wx.NewId()
ID_TOOL_INPUTBARCODE = wx.NewId()
ID_VIEW_OBJS = wx.NewId()
ID_VIEW_LOG = wx.NewId()
ID_VIEW_COUNT = wx.NewId()

class MainFrame(wx.Frame):
    
    def __init__(self):
        wx.Frame.__init__(self, None, title = u"上海铭衍--四轮定位", 
                          style = wx.DEFAULT_FRAME_STYLE | wx.MAXIMIZE)
        self.views = []
        
        self.SetMinSize((800,600))
        
        self.m_userStatus = False #user administrator login status, default is False;if logined,set True
        
        pnl = wx.Panel(self)
        self.pnl = pnl
        
        self.mgr = wx.aui.AuiManager()
        self.mgr.SetManagedWindow(pnl)
        
        self.nb = FNB.FlatNotebook(pnl, agwStyle = FNB.FNB_VC8 | FNB.FNB_DCLICK_CLOSES_TABS | FNB.FNB_X_ON_TAB)
        isz = (16,16)
        il = wx.ImageList(isz[0], isz[1])
        il.Add(wx.Bitmap('images/module.png'))
        il.Add(wx.Bitmap('images/method.gif'))
        il.Add(wx.Bitmap('images/plus.png'))
        self.nb.AssignImageList(il)
        
        leftPanel = DomainWindow.DomainPanel(pnl, self)
        
        self.log = LogWindow.LogPanel(pnl)
        debug.SetView(self.log)
        error.SetView(self.log)
        
        self.countpanel = CountWindow.CountPanel(pnl)
        
        self.BuildMenuBar()
        
        self.BuildToolBar()
        
        self.statusbar = self.CreateStatusBar(3)
        
        # Use the aui manager to set up everything
        self.mgr.AddPane(self.nb, wx.aui.AuiPaneInfo().CenterPane().Name("Notebook"))
        
        self.mgr.AddPane(self.log,
                         wx.aui.AuiPaneInfo().
                         Bottom().BestSize((200, 150)).
                         MinSize((100, 60)).
                         Floatable(True).FloatingSize((500, 160)).
                         Caption(u"事件消息").
                         CloseButton(True).
                         Name("LogWindow"))
        self.mgr.AddPane(self.countpanel,
                         wx.aui.AuiPaneInfo().
                         Bottom().BestSize((620, 170)).
                         MinSize((600, 60)).
                         Floatable(True).FloatingSize((600, 160)).
                         Caption(u"生产信息").
                         CloseButton(True).
                         Name("CountWindow"))
        self.mgr.AddPane(leftPanel,
                         wx.aui.AuiPaneInfo().
                         Left().Layer(1).BestSize((120, -1)).
                         MinSize((60, -1)).
                         Floatable(True).FloatingSize((240, 700)).
                         Caption(u"E18 对象").
                         CloseButton(True).
                         Name("ObjectTree"))

        self.mgr.LoadPerspective(app.pref.layout)
        self.mgr.Update()

        self.mgr.SetFlags(self.mgr.GetFlags() ^ wx.aui.AUI_MGR_TRANSPARENT_DRAG)
        
        self.SetStatusText(u"上海铭衍E18系统欢迎使用")
        #####################################################################
        self.pnl.Bind(wx.aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.nb.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnPageClosing)
        
        self.Maximize()
        
        self.Init()
        
    def Init(self):
        self.menuBar.FindItemById(ID_VIEW_OBJS).Check(self.mgr.GetPane("ObjectTree").IsShown())
        self.menuBar.FindItemById(ID_VIEW_LOG).Check(self.mgr.GetPane("LogWindow").IsShown())
        self.menuBar.FindItemById(ID_VIEW_COUNT).Check(self.mgr.GetPane("CountWindow").IsShown())
        
        try:
            app.condomain.BeginWork()
            app.domain.BeginWork()
        except:
            wx.MessageBox(u"连接拧紧设备出现故障")
        
    def OnPaneClose(self, event):

        caption = event.GetPane().name

        if caption in ["LogWindow", "ObjectTree", "CountWindow"]:
            msg = u"您确定要关闭面板吗？如果需要关闭，你可以从菜单中重新调出该面板"
            dlg = wx.MessageDialog(self, msg, "提示",
                                   wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)

            if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
                event.Veto()
                
            if caption == "LogWindow":
                self.menuBar.FindItemById(ID_VIEW_LOG).Check(False)
            elif caption == "ObjectTree":
                self.menuBar.FindItemById(ID_VIEW_OBJS).Check(False)
            elif caption == "CountWindow":
                self.menuBar.FindItemById(ID_VIEW_COUNT).Check(False)
            dlg.Destroy()
            
    def OnViewObjs(self, evt):
        item = self.menuBar.FindItemById(ID_VIEW_OBJS)
        
        if item.IsChecked():
            self.mgr.GetPane("ObjectTree").Show(True)
        else:
            self.mgr.GetPane("ObjectTree").Hide()
            
        self.mgr.Update()
    
    def OnViewLog(self, evt):
        item = self.menuBar.FindItemById(ID_VIEW_LOG)
        
        if item.IsChecked():
            self.mgr.GetPane("LogWindow").Show(True)
        else:
            self.mgr.GetPane("LogWindow").Hide()
            
        self.mgr.Update()
    
    def OnViewCount(self, evt):
        item = self.menuBar.FindItemById(ID_VIEW_COUNT)
        
        if item.IsChecked():
            self.mgr.GetPane("CountWindow").Show(True)
        else:
            self.mgr.GetPane("CountWindow").Hide()
            
        self.mgr.Update()
        
    def BuildMenuBar(self):
        self.menuBar = wx.MenuBar()
        
        menu = wx.Menu()
        menu.AppendSeparator()
        item = wx.MenuItem(menu, wx.ID_EXIT, u"退出", u"退出应用程序", wx.ITEM_NORMAL)
        menu.AppendItem(item)
        m_userLoginItem = wx.MenuItem(menu, wx.ID_ANY, u"用户登录", u"用户账号登录", wx.ITEM_NORMAL)
        menu.AppendItem(m_userLoginItem)
        self.Bind(wx.EVT_MENU, self.OnLoginAcc, id = m_userLoginItem.GetId())
        self.m_userExitItem = wx.MenuItem(menu, wx.ID_ANY, u"用户退出", u"用户帐号退出", wx.ITEM_NORMAL)
        self.m_userExitItem.Enable(False)
        self.Bind(wx.EVT_MENU, self.OnLogoutAcc, id = self.m_userExitItem.GetId())
        menu.AppendItem(self.m_userExitItem)
        #self.Bind(wx.EVT_MENU, self.OnClose, id = item.GetId())
        self.menuBar.Append(menu, u'文件')
        
        menu = wx.Menu()
        item = wx.MenuItem(menu, ID_VIEW_OBJS, u"导航栏", u"打开/关闭导航栏", wx.ITEM_CHECK)
        menu.AppendItem(item)
        self.Bind(wx.EVT_MENU, self.OnViewObjs, id = item.GetId())
        item = wx.MenuItem(menu, ID_VIEW_LOG, u"日志", u"打开/关闭日志栏", wx.ITEM_CHECK)
        menu.AppendItem(item)
        self.Bind(wx.EVT_MENU, self.OnViewLog, id = item.GetId())
        item = wx.MenuItem(menu, ID_VIEW_COUNT, u"生产信息", u"打开/关闭生产信息栏", wx.ITEM_CHECK)
        menu.AppendItem(item)
        self.Bind(wx.EVT_MENU, self.OnViewCount, id = item.GetId())
        self.menuBar.Append(menu, u'视图')
        
        menu = wx.Menu()
        item = wx.MenuItem(menu, ID_EDIT_COOR, u"坐标系...", wx.EmptyString, wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnEditCoor, id = item.GetId())
        menu.AppendItem(item) ###### finished
        menu.AppendSeparator()
        item = wx.MenuItem(menu, ID_EDIT_PREF, u"首选项...", wx.EmptyString, wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnPreference, id = item.GetId())
        menu.AppendItem(item) ####### finished
        self.menuBar.Append(menu, u"编辑")
        #self.Bind(wx.EVT_MENU, self.OnQuery, id = item.GetId())
        
        ## 添加查询菜单
        menu = wx.Menu()
        item = wx.MenuItem(menu, ID_EDIT_USER, u"用户管理...", u"新建/删除用户", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnUserManager, id = item.GetId())
        menu.AppendItem(item) ##### finished
        item = wx.MenuItem(menu, ID_QUERY_CATEGORY, u"定义产品分类...", u"新建/删除产品分类", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnEditCategory, id = item.GetId())
        menu.AppendItem(item) ##### finished
        item = wx.MenuItem(menu, ID_QUERY_PRODUCTTYPE, u"产品类型...", u"新建/删除产品类型", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnEditProductType, id = item.GetId())
        menu.AppendItem(item)##### finished
        item = wx.MenuItem(menu, ID_QUERY_ENTITY, u"工作实体...", u"新建/删除工作实体", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnEditEntity, id = item.GetId())
        menu.AppendItem(item) #### finished
        item = wx.MenuItem(menu, ID_QUERY_CALIBLOG, u"标定历史查询...", u"查询标定历史记录", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnQueryCalibLog, id = item.GetId())
        menu.AppendItem(item)#
        
       
        self.menuBar.Append(menu, u"数据库")
        
        item = wx.MenuItem(menu, ID_QUERY_PART, u"产品查询...", u"查询产品组装及加工信息", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnQueryPart, id = item.GetId())
        menu.AppendItem(item)
        
        ## 添调试菜单
        menu = wx.Menu()
        item = wx.MenuItem(menu, ID_TOOL_CALIB, u"标定向导...", u"使用标定向导进行标定", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnToolCalib, id = item.GetId())
        menu.AppendItem(item)   ### finished
        
        item = wx.MenuItem(menu, ID_TOOL_CLRCOUNT, u"生产计数清零", u"生产计数清零", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnToolClrCount, id = item.GetId())
        menu.AppendItem(item)
        
        item = wx.MenuItem(menu, ID_TOOL_CLEARRES, u"清除结果信号", u"清除结果信号", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnToolClearRes, id = item.GetId())
        menu.AppendItem(item)
        
        item = wx.MenuItem(menu, ID_TOOL_INPUTBARCODE, u"人工输入条码", u"人工输入条码", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnToolInputBarcode, id = item.GetId())
        menu.AppendItem(item)
        
        item = wx.MenuItem(menu, ID_TOOL_PYCRUST, u"PyCrust...", u"调用PyCrust调试程序", wx.ITEM_NORMAL)
        self.Bind(wx.EVT_MENU, self.OnToolPyCrust, id = item.GetId())
        menu.AppendItem(item)
        self.menuBar.Append(menu, u"工具")
        
        menu = wx.Menu()
        item = wx.MenuItem(menu, wx.ID_ABORT, u"关于", wx.EmptyString, wx.ITEM_NORMAL)
        menu.AppendItem(item)
        self.menuBar.Append(menu, u"帮助")
        self.Bind(wx.EVT_MENU, self.OnAbout,id = item.GetId())
        
        self.SetMenuBar(self.menuBar)
      
    def OnLoginAcc(self, event):
        if self.m_userStatus == True:
            wx.MessageBox(u"用户已经登录，无法重复登录，请稍后操作！")
            return
        else:
            from UserLoginDlg import UserLoginDlg
            userLoginDlg = UserLoginDlg(self)
            userLoginDlg.ShowModal();
            
       
        
    def OnLogoutAcc(self, event):
        if self.m_userStatus == False:
            wx.MessageBox(u"用户尚未登录无法完成操作！")
            return
        else:
            self.m_userStatus = False
            self.m_userExitItem.Enable(False)
        
    def BuildToolBar(self):
        tb = self.CreateToolBar(wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT | wx.TB_TEXT)
        tb.SetToolBitmapSize((32,32))
        
        plan_bmp =  wx.Bitmap('images/GOMPlayer.png')
        print_bmp = wx.Bitmap('images/Counter.png')
        reprint_png = wx.Bitmap('images/Half-Life.png')
        crust_png = wx.Bitmap('images/Photoshop.png')
        part_png = wx.Bitmap('images/Chrome.png')
        pref_png = wx.Bitmap('images/ooVoo.png')
        clearres_png = wx.Bitmap('images/Half-Life.png')
        
        tb.AddLabelTool(ID_TOOL_CALIB, u"标定向导", plan_bmp, shortHelp=u"使用标定向导", longHelp=u"使用标定向导进行标定")
        tb.AddSeparator()
        tb.AddLabelTool(ID_QUERY_PART, u"产品查询", part_png, shortHelp=u"产品加工数据", longHelp=u"查询产品加工数据")
        tb.AddSeparator()
        tb.AddLabelTool(ID_TOOL_PYCRUST, u"PyCrust", crust_png, shortHelp=u"调试环境", longHelp=u"打开调试环境")
        tb.AddSeparator()
        tb.AddLabelTool(ID_EDIT_PREF, u"参数", pref_png, shortHelp=u"首选参数", longHelp=u"打开参数设置对话框")
        tb.AddSeparator()
        st = wx.StaticText(tb, label = u"型号选择")
        st.SetFont(wx.Font( 13, 70, 90, 92, False, wx.EmptyString ))
        tb.AddControl(st)
        choices = [''] + Model.MPartTypes.GetNames()
        self.cbTypeChoice = wx.Choice(tb, size = (100,-1), choices = choices)
        try:
            self.cbTypeChoice.SetSelection(choices.index(Globals.pref.part_type))
        except:
            self.cbTypeChoice.SetSelection(0)
        tb.AddControl(self.cbTypeChoice)
        tb.AddSeparator()
        
        tb.AddLabelTool(ID_TOOL_CLEARRES, u"清除信号", clearres_png, shortHelp=u"请除结果信号", longHelp=u"请除结果信号")
        tb.AddSeparator()
        
        tb.AddLabelTool(ID_TOOL_CLRCOUNT, u"计数清零", clearres_png, shortHelp=u"生产计数清零", longHelp=u"生产计数清零")
        tb.AddSeparator()
        
        self.runmsg = wx.StaticText(tb, label = u"等待工件就绪", size = (300, -1))
        self.runmsg.SetFont(wx.Font( 20, 70, 90, 92, False, wx.EmptyString ))
        self.runmsg.SetForegroundColour(wx.Colour(255, 0, 0))
        tb.AddControl(self.runmsg)
        
        tb.Realize()
        
        self.cbTypeChoice.Bind(wx.EVT_CHOICE, self.OnPartTypeChoice)
            
    def CreateMainView(self):
        con = app.viewcon
        if con.GetMainView() in self.views:
            self.nb.SetSelection(self.nb.GetPageIndex(con.GetMainView()))
            return
        import MainView as MV
        
        book = MV.MainView(self.nb)
        book.SetController(con)
        
        con.SetMainView(book)
        self.views.append(book)
        
        self.nb.AddPage(book, u'图形视图', True, 0)
        
    def CreateResultView(self):
        con = app.viewcon
        if con.GetResultView() in self.views:
            self.nb.SetSelection(self.nb.GetPageIndex(con.GetResultView()))
            return
        import MainView as MV
        
        book = MV.ResultView(self.nb)
        book.SetController(con)
        
        con.SetResultView(book)
        self.views.append(book)
        
        self.nb.AddPage(book, u'结果视图', True, 0)
        
    def CreateInfoView(self):
        pass
        
    def CreateManualView(self):
        import ManualWindow as MW
        dlg = MW.ManualFrame(self)
        dlg.Show()
        
    def CreateLCambAngleSpcView(self):
        win = SPCWindow.SPCWindow(self, app.domain.max_lcambangle, app.domain.min_lcambangle, self.QueryLCambAngle)
        win.Show()
    
    def CreateLConsAngleSpcView(self):
        win = SPCWindow.SPCWindow(self, app.domain.max_lconsangle, app.domain.min_lconsangle, self.QueryLConsAngle)
        win.Show()
    
    def CreateRCambAngleSpcView(self):
        win = SPCWindow.SPCWindow(self, app.domain.max_rcambangle, app.domain.min_rcambangle, self.QueryRCambAngle)
        win.Show()
    
    def CreateRConsAngleSpcView(self):
        win = SPCWindow.SPCWindow(self, app.domain.max_rconsangle, app.domain.min_rconsangle, self.QueryRConsAngle)
        win.Show()
        
    def QueryLCambAngle(self, mode, *args):
        if mode == 1:
            begintime = args[0]
            endtime = args[1]
            
            r = Database.MPart.select(AND(Database.MPart.q.createtime > begintime, Database.MPart.q.createtime < endtime))
            return [[x.createtime, x.lcambangle] for x in r ]
        elif mode ==2:
            count = args[0]
            
            r = Database.MPart.select(limit = count)
            return [[x.createtime, x.lcambangle] for x in r ]
        elif mode == 3:
            r = Database.MPart.select()
            return [[x.createtime, x.lcambangle] for x in r ]
        else:
            return []
    
    def QueryLConsAngle(self, mode, *args):
        if mode == 1:
            begintime = args[0]
            endtime = args[1]
            
            r = Database.MPart.select(AND(Database.MPart.q.createtime > begintime, Database.MPart.q.createtime < endtime))
            return [[x.createtime, x.lconsangle] for x in r ]
        elif mode ==2:
            count = args[0]
            
            r = Database.MPart.select(limit = count)
            return [[x.createtime, x.lconsangle] for x in r ]
        elif mode == 3:
            r = Database.MPart.select()
            return [[x.createtime, x.lconsangle] for x in r ]
        else:
            return []
    
    def QueryRCambAngle(self, mode, *args):
        if mode == 1:
            begintime = args[0]
            endtime = args[1]
            
            r = Database.MPart.select(AND(Database.MPart.q.createtime > begintime, Database.MPart.q.createtime < endtime))
            return [[x.createtime, x.rcambangle] for x in r ]
        elif mode ==2:
            count = args[0]
            
            r = Database.MPart.select(limit = count)
            return [[x.createtime, x.rcambangle] for x in r ]
        elif mode == 3:
            r = Database.MPart.select()
            return [[x.createtime, x.rcambangle] for x in r ]
        else:
            return []
    
    def QueryRConsAngle(self, mode, *args):
        if mode == 1:
            begintime = args[0]
            endtime = args[1]
            
            r = Database.MPart.select(AND(Database.MPart.q.createtime > begintime, Database.MPart.q.createtime < endtime))
            return [[x.createtime, x.rconsangle] for x in r ]
        elif mode ==2:
            count = args[0]
            
            r = Database.MPart.select(limit = count)
            return [[x.createtime, x.rconsangle] for x in r ]
        elif mode == 3:
            r = Database.MPart.select()
            return [[x.createtime, x.rconsangle] for x in r ]
        else:
            return []
        
    def SetRunMsg(self, msg, colour = wx.Colour(255, 0, 0)):
        self.runmsg.SetForegroundColour(colour)
        self.runmsg.SetLabel(msg)
    
    def OnAbout(self, evt):
        wx.MessageBox(u"Version : 0.8.0", u"关于")
        
    def OnClose(self, evt):
        ret = wx.MessageBox(u"本程序如果停止运行您将失去对机器的控制，\n您确定要退出吗?", u"重要提示", wx.YES_NO | wx.ICON_QUESTION)
        if  ret == wx.NO:
            return
        self.log.StopBlink()
        app.pref.layout = self.mgr.SavePerspective()
        app.pref.save()
        self.Destroy()
        
    def OnExit(self, evt):
        self.Close()
        
    def OnUserManager(self, evt):
        if self.m_userStatus == False:
            wx.MessageBox(u"当前用户没有权限进行该操作，请登录权限更高的用户!")
            return
        else:
            import UserWindow
            dlg = UserWindow.UserDialog(self)
            dlg.ShowModal()
        
    def OnEditCategory(self, evt):
        if self.m_userStatus == False:
            wx.MessageBox(u"当前用户没有权限进行该操作，请登录权限更高的用户！")
            return
        import CategoryWindow
        dlg = CategoryWindow.CategoryDialog(self)
        dlg.ShowModal()
        
    def OnEditCoor(self, evt):
        if self.m_userStatus == False:
            wx.MessageBox(u"当前用户没有权限进行该操作，请登录权限更高的用户！")
            return
        import CoordinateDialog
        dlg = CoordinateDialog.CoordinateDialog(self)
        dlg.ShowModal()
        
    def OnEditProductType(self, evt):
        if self.m_userStatus == False:
            wx.MessageBox(u"当前用户没有权限进行该操作，请登录权限更高的用户！")
            return
        import ProductWindow
        dlg = ProductWindow.ProductTypeDialog(self)
        dlg.ShowModal()
        self.cbTypeChoice.Clear()
        choices = [''] + Model.MPartTypes.GetNames()
        self.cbTypeChoice.AppendItems(choices)
        self.cbTypeChoice.SetSelection(choices.index(Globals.pref.part_type))
        app.domain.SetPartType(self.cbTypeChoice.GetStringSelection())
        
    def OnEditEntity(self, evt):
        if self.m_userStatus == False:
            wx.MessageBox(u"当前用户没有权限进行该操作，请登录权限更高的用户！")
            return
        import StationWindow
        dlg = StationWindow.EntityDialog(self)
        dlg.ShowModal()
        
    def OnQueryPart(self, evt):
        import ProductWindow
        dlg = ProductWindow.PartQueryDialog(self)
        dlg.ShowModal()

    def OnToolPyCrust(self, evt):
        import  wx.py   as  py
        
        win = py.crust.CrustFrame(self)
        win.Center()
        win.Show()
        
    def OnPreference(self, evt):
        if self.m_userStatus == False:
            wx.MessageBox(u"当前用户没有权限进行该操作,请登录权限更高的用户！")
            return
        else:
            import PrefDialog
            dlg = PrefDialog.PrefDialog(self)
            dlg.SavePref = app.viewcon.OnSavePref
            dlg.ShowModal()
    
    def OnPageClosing(self, evt):
        page = self.nb.GetPage(evt.GetSelection())
        for i, view in enumerate(self.views):
            if page is view:
                view.DetachController()
                del(self.views[i])
                break
        evt.Skip()
        
    def OnPartTypeChoice(self, evt):
        parttype = evt.GetString()
        if not parttype in Globals.high_types+Globals.low_types+Globals.mid_types:
            app.viewcon.ShowBusyMessage(u'%s与高、中、低配关系不存在' % parttype)
            try:
                self.cbTypeChoice.SetSelection(choices.index(Globals.pref.part_type))
            except:
                self.cbTypeChoice.SetSelection(0)
            return
        
        app.domain.SetPartType(parttype)
        Globals.pref.part_type = parttype
        Globals.pref.save()
        
    def OnToolClearRes(self, evt):
        app.condomain.Green()
        
    def OnToolCalib(self, evt):
        if self.m_userStatus == False:
            wx.MessageBox(u"当前用户没有权限进行该操作，请登录权限更高的用户！")
            return
        dlg = CalibWindow.CalibWindow(self)
        dlg.Show()
    
    def OnToolClrCount(self, evt):
        self.countpanel.Clear()
        app.domain.ClearCount()
        
    def OnUpdateCount(self, okcnt, nokcnt, firsttime, lasttime):
        self.countpanel.Set(okcnt, nokcnt, firsttime, lasttime)
        
    def OnQueryCalibLog(self, evt):
        import CalibWindow
        dlg = CalibWindow.CalibLogWindow(self)
        dlg.ShowModal()
        
    def OnToolInputBarcode(self, evt):
        dlg = wx.TextEntryDialog(self, u"请输入条码", u"输入条码")
        if dlg.ShowModal() == wx.ID_OK:
            barcode = dlg.GetValue()
            if len(barcode) < 1:
                wx.MessageBox(u"输入不能为空")
                return
            app.domain.OnScanBarcode(barcode + '\r')
        
    def SetPartType(self, type):
        self.cbTypeChoice.SetStringSelection(type)